package cn.itcast.Rainbow_self_mention.Server;

import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import androidx.annotation.Nullable;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapView;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.InetSocketAddress;

import cn.itcast.Rainbow_self_mention.Activity.Map;
import cn.itcast.Rainbow_self_mention.Dao.SqlHelper;
import cn.itcast.Rainbow_self_mention.Tools.imfor;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class MapServer extends Service {
    private MapView mMapView = null;
    BaiduMap mBaiduMap = null;
    LocationClient mLocationClient = null;
    Boolean link = false;
    String ip = imfor.ip;
    ;
    sender sender;
    Handler map = Map.handler;
    Double x, y;
    SqlHelper hp = new SqlHelper(this);
    Channel ch1;
    int i = 0;
    int n = 50;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        sender = new sender();
        return sender;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        SQLiteDatabase sq = hp.getWritableDatabase();
        sq.delete("box", null, null);
        sq.close();
        SDKInitializer.initialize(getApplicationContext());
        mMapView = new MapView(this);
        mBaiduMap = mMapView.getMap();
        init_location();
        mBaiduMap.setMyLocationEnabled(true);
        if (!mLocationClient.isStarted()) {
            mLocationClient.start();
        }
    }

    public void getdis() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture bs1 = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(final NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LineBasedFrameDecoder(2048));
                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast("input", new ChannelInboundHandlerAdapter() {
                            public void channelActive(ChannelHandlerContext ctx) {
                                link = true;
                                Message m = map.obtainMessage();
                                Bundle bundle = new Bundle();
                                bundle.putString("sentresult", "34");
                                m.setData(bundle);
                                map.sendMessage(m);
                                String msg = "{" +
                                        "\"Cop\":" + "\"1\"," +
                                        "\"x\":" + "\"" + x + "\"," +
                                        "\"y\":" + "\"" + y + "\"" +
                                        "}" + '\n';
                                ch.writeAndFlush(msg);

                            }

                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                super.channelRead(ctx, msg);
                                operation(msg);

                            }

                            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                                ctx.fireChannelInactive();
                                link = false;
                                Message m = map.obtainMessage();
                                Bundle bundle = new Bundle();
                                bundle.putString("sentresult", "35");
                                m.setData(bundle);
                                map.sendMessage(m);
                            }
                        });
                    }
                })
                .connect(new InetSocketAddress(ip, 9000));
        ch1 = bs1.channel();
    }

    public class sender extends Binder {
        public void relink() {
            getdis();
        }
        //定位当前位置
        public Double nx, ny;

        public void getnow() {
            nx = x;
            ny = y;
        }


        public void get() {
            String msg = "{" +
                    "\"Cop\":" + "\"1\"," +
                    "\"x\":" + "\"" + x + "\"," +
                    "\"y\":" + "\"" + y + "\"" +
                    "}" + '\n';
            ch1.writeAndFlush(msg);
        }
    }

    public void operation(Object msg) throws JSONException {

        String ms = msg.toString();
        JSONObject jsonObject = new JSONObject(ms);

        Log.i("收到信息：", ms);
        if (jsonObject.getString("Cop").equals("11")) {
            SQLiteDatabase db = hp.getReadableDatabase();
            Cursor cursor = db.query("box", new String[]{"box_id"}, "box_id=?", new String[]{jsonObject.getString("box_id")}, null, null, null);
            cursor.moveToFirst();
            if (cursor.getCount() == 0) {
                cursor = db.query("box", null, null, null, null, null, null);
                cursor.moveToFirst();
                int c = cursor.getCount() + 1;
                Log.i("服务当前插入柜子表数量：", c + "");
                SQLiteDatabase sq = hp.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put("_id", c);
                values.put("box_id", jsonObject.getInt("box_id"));
                values.put("longitude", jsonObject.getDouble("lon"));
                values.put("lantitude", jsonObject.getDouble("lan"));
                values.put("distance", jsonObject.getDouble("range"));
                values.put("location", jsonObject.getString("location"));
                sq.insert("box", null, values);
                cursor.close();
                sq.close();
                Message m = map.obtainMessage();
                Bundle bundle = new Bundle();
                bundle.putString("sentresult", "1");
                m.setData(bundle);
                map.sendMessage(m);
                return;
            }
            if (cursor.getCount() == 1) {
                cursor = db.query("box", null, null, null, null, null, null);
                cursor.moveToFirst();
                int c = cursor.getCount() + 1;
                Log.i("服务当前更新柜子表数量：", c + "");
                SQLiteDatabase sq = hp.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put("box_id", jsonObject.getInt("box_id"));
                values.put("longitude", jsonObject.getDouble("lon"));
                values.put("lantitude", jsonObject.getDouble("lan"));
                values.put("distance", jsonObject.getDouble("range"));
                values.put("location", jsonObject.getString("location"));
                sq.update("box", values, "box_id=?", new String[]{jsonObject.getString("box_id")});
                cursor.close();
                sq.close();
                Message m = map.obtainMessage();
                Bundle bundle = new Bundle();
                bundle.putString("sentresult", "1");
                m.setData(bundle);
                map.sendMessage(m);
                return;
            }

        }
        if (jsonObject.getString("Cop").equals("12")) {
            Log.i("执行更新柜子表完成", 1 + "");
            Message m = map.obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString("sentresult", "2");
            m.setData(bundle);
            map.sendMessage(m);
            return;
        }


    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null || mMapView == null) {
                return;
            }
            x = location.getLongitude();
            y = location.getLatitude();
            go();
            i = 1;


        }
    }

    public void go() {
        if (i == 0) {
            getdis();
        }

    }

    public void init_location() {
        mBaiduMap.setMyLocationEnabled(true);
        mLocationClient = new LocationClient(this);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);
        option.setCoorType("bd09ll");
        option.setScanSpan(1000);
        option.setIsNeedAddress(true);
        option.setIsNeedLocationDescribe(true);
        option.setNeedDeviceDirect(true);
        mLocationClient.setLocOption(option);
        MyLocationListener myLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myLocationListener);

    }
}
